package cn.wolfcode.p2p.util;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户上下文
 */
public class UserContext {


    private static final String VERIFYCODE_IN_SESSION = "verifycode_in_session";
    private static final String LOGININFO_IN_SESSION = "logininfo";


    /**
     * 获取sesison
     */
    public static HttpSession getSession(){
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request.getSession();
    }

    /**
     * 保存验证码发送记录到session
     */
    public static void setVerifyCodeVO(VerifyCodeVO vo){
        //拿session
        getSession().setAttribute(VERIFYCODE_IN_SESSION,vo);
    }

    /**
     * 从session中获取验证码发送记录
     */
    public static VerifyCodeVO getVerifyCodeVO(){
        return (VerifyCodeVO)getSession().getAttribute(VERIFYCODE_IN_SESSION);
    }

    /**
     * 将登录用户信息存放到session中
     * @param loginInfo
     */
    public static void setCurrentUser(LoginInfo loginInfo){
        getSession().setAttribute(LOGININFO_IN_SESSION, loginInfo);
    }
    /**
     * 将登录用户信息从session中取出来
     */
    public static LoginInfo getCurrentUser(){
        return (LoginInfo)getSession().getAttribute(LOGININFO_IN_SESSION);
    }

    /**
     * 获取访问时的Ip地址
     * @return
     */
    public static String getIp() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request.getRemoteAddr();
    }

}
